package com.linksoul.controller;

import com.linksoul.annotation.LogMBTIRequest;
import com.linksoul.common.Result;
import com.linksoul.domain.TestDimensionDetail;
import com.linksoul.domain.dto.QuestionDTO;
import com.linksoul.domain.dto.SubmitAnswerDTO;
import com.linksoul.exception.MbtiException;
import com.linksoul.service.CertificateService;
import com.linksoul.service.MbtiCalculatorService;
import com.linksoul.service.MbtiService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/05/01/12:28
 **/
@RestController
@RequestMapping("/api/mbti")
@RequiredArgsConstructor
public class MbtiController {
    private final MbtiService mbtiService;
    private final MbtiCalculatorService calculatorService;
    @Autowired
    private CertificateService certificateService;

    // 获取所有MBTI问题
    @GetMapping("/questions")
    @LogMBTIRequest
    public Result<List<QuestionDTO>> getAllQuestions() {
        return Result.success(mbtiService.getTestQuestions());
    }

    // 按维度获取问题
    @GetMapping("/questions/{dimension}")
    public Result<List<QuestionDTO>> getDimensionQuestions(
            @PathVariable String dimension) {
        return Result.success(mbtiService.getQuestionsByDimension(dimension));
    }

    // 异常处理
    @ExceptionHandler(MbtiException.class)
    public Result<?> handleMbtiException(MbtiException e) {
        return Result.fail(e.getCode(), e.getMessage());
    }



    @PostMapping("/submit")
    public Result<String> submitTest(
      @RequestBody SubmitAnswerDTO submitAnswerDTO
    ) {
        try {
            String mbtiType = calculatorService.calculateMbti(submitAnswerDTO.getUserAnswers(), submitAnswerDTO.getRequestId());
            certificateService.generateCertificate(submitAnswerDTO.getRequestId(),"defaut","web");
            return Result.success(mbtiType);
        } catch (Exception e) {
            return Result.fail(500, "MBTI计算失败: " + e.getMessage());
        }
    }

    /**
     * 获取维度得分详情
     */
    @GetMapping("/detail")
    public Result<TestDimensionDetail> getDimensionDetail(@RequestParam String requestId) {
        TestDimensionDetail detail = mbtiService.getDimensionDetail(requestId);
        return Result.success(detail);
    }
}